package com.bx.implatform.config;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author chilson
 * @date 2025-09-27 10:55:43
 */
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class GlobalDataManager {
    private final Map<String, Object> dataStore = new ConcurrentHashMap<>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 存储数据
     */
    public void put(String key, Object data) {
        lock.writeLock().lock();
        try {
            dataStore.put(key, data);
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 获取数据
     */
    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        lock.readLock().lock();
        try {
            return (T) dataStore.get(key);
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 获取数据，如果不存在返回默认值
     */
    @SuppressWarnings("unchecked")
    public <T> T get(String key, T defaultValue) {
        lock.readLock().lock();
        try {
            T value = (T) dataStore.get(key);
            return value != null ? value : defaultValue;
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 检查是否包含key
     */
    public boolean containsKey(String key) {
        lock.readLock().lock();
        try {
            return dataStore.containsKey(key);
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 移除数据
     */
    public void remove(String key) {
        lock.writeLock().lock();
        try {
            dataStore.remove(key);
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 清空所有数据
     */
    public void clear() {
        lock.writeLock().lock();
        try {
            dataStore.clear();
        } finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 获取所有键
     */
    public Set<String> keySet() {
        lock.readLock().lock();
        try {
            return new HashSet<>(dataStore.keySet());
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 获取数据大小
     */
    public int size() {
        lock.readLock().lock();
        try {
            return dataStore.size();
        } finally {
            lock.readLock().unlock();
        }
    }
}
